﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;

namespace Tess.CSharp
{
    class Program
    {
        [DllImport("tess")]
        private static extern bool Recognize(
            [MarshalAs(UnmanagedType.LPStr)]string lpLanguage,		/*e.g. eng, chs, null means eng*/
            bool numeric_mode,
            IntPtr buffer,	/*image buffer*/
            int bytes_per_pixel,
            int bytes_per_line,
            int left,
            int top,
            int width,
            int height,
            [MarshalAs(UnmanagedType.LPStr)]StringBuilder lpText,			/*output text buffer*/
            int nSize			/*maximize size*/
            );

        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("tess-cs image");
                return;
            }

            Bitmap img = new Bitmap(args[0]);

            BitmapData data = img.LockBits(
                new Rectangle(0, 0, img.Width, img.Height),
                ImageLockMode.ReadOnly,
                PixelFormat.Format32bppArgb);

            StringBuilder text = new StringBuilder(64);
            Recognize(null, true, data.Scan0,
                GetPixelFormatSize(data.PixelFormat) / 8, data.Stride,
                0, 0, data.Width, data.Height,
                text, 64);

            Console.WriteLine(text.ToString());

            img.UnlockBits(data);
        }

        private static int GetPixelFormatSize(PixelFormat pixfmt)
        {
            return ((int)pixfmt >> 8) & 0xff;
        }
    }
}
